package com.ruoyi.smart.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.smart.domain.*;
import com.ruoyi.smart.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 测试Controller
 * 
 * @author ruoyi
 * @date 2022-03-14
 */
@Api("数据上传")
@RestController
@RequestMapping("/smart/threePart")
public class ThreePartController extends BaseController
{
    @Autowired
    private ISmartTestService smartTestService;
    @Autowired
    private ISmartProductTestService smartProductTestService;
    @Autowired
    private ISmartProcessDataService smartProcessDataService;
    @Autowired
    private ISmartModDataService smartModDataService;
    @Autowired
    private ISmartProductService smartProductService;
    @Autowired
    private ISmartProductTestRecordService smartProductTestRecordService;

    /**
     * 查询测试列表
     */
    @ApiOperation("功能测试接口")
    @PostMapping("/functionTest")
    public AjaxResult functionTest(@RequestBody JSONObject jsonParam)
    {
        if(containsSqlInjection(jsonParam)) return AjaxResult.success("数据不正常");
        String str= jsonParam.toJSONString();
        System.out.println("接收到数据:"+str);
        SmartProductTest smartProductTest=new SmartProductTest();
        smartProductTest.setDeviceId(jsonParam.getJSONObject("device").getString("id"));
        smartProductTest.setUserId(jsonParam.getJSONObject("device").getString("usr"));
        smartProductTest.setCurrent(jsonParam.getJSONObject("switch").getJSONArray("currval").get(0).toString());
        smartProductTest.setVoltage(jsonParam.getJSONObject("switch").getJSONArray("currval").get(1).toString());
        smartProductTest.setTestResult(jsonParam.getJSONObject("switch").getString("state"));
        JSONObject jsonArr= jsonParam.getJSONObject("switch").getJSONObject("wave");
        List<SmartProductTestWaveform> list=new ArrayList<>();
        for(String key:jsonArr.keySet()){
            SmartProductTestWaveform smartProductTestWaveform=new SmartProductTestWaveform();
            smartProductTestWaveform.setData(jsonArr.get(key).toString());
            list.add(smartProductTestWaveform);
        }
        smartProductTest.setSmartProductTestWaveformList(list);
        smartProductTestService.insertSmartProductTest(smartProductTest);
        return AjaxResult.success(jsonParam);
    }

    /**
     * 查询测试列表
     */
    @ApiOperation("新设备信息")
    @PostMapping("/newDevice")
    public AjaxResult newDevice(@RequestBody JSONObject jsonParam)
    {
        if(containsSqlInjection(jsonParam)) return AjaxResult.success("数据不正常");
        String str= jsonParam.toJSONString();
        System.out.println("接收到数据:"+str);
        return AjaxResult.success(jsonParam);
    }

    /**
     * 导出测试列表
     */
    @PreAuthorize("@ss.hasPermi('system:test:export')")
    @Log(title = "测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SmartTest smartTest)
    {
        if(containsSqlInjection(smartTest)) return ;
        List<SmartTest> list = smartTestService.selectSmartTestList(smartTest);
        ExcelUtil<SmartTest> util = new ExcelUtil<SmartTest>(SmartTest.class);
        util.exportExcel(response, list, "测试数据");
    }

    /**
     * 获取测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:test:query')")
    @GetMapping(value = "/{id}")
    //@ApiOperation("获取测试详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        if(containsSqlInjection(id)) return AjaxResult.success("数据不正常");
        return AjaxResult.success(smartTestService.selectSmartTestById(id));
    }

    /**
     * 新增测试
     */
    @PreAuthorize("@ss.hasPermi('system:test:add')")
    @Log(title = "测试", businessType = BusinessType.INSERT)
    @PostMapping
    //@ApiOperation("添加")
    public AjaxResult add(@RequestBody SmartTest smartTest)
    {
        if(containsSqlInjection(smartTest)) return AjaxResult.success("数据不正常");
        return toAjax(smartTestService.insertSmartTest(smartTest));
    }

    /**
     * 修改测试
     */
    @PreAuthorize("@ss.hasPermi('system:test:edit')")
    @Log(title = "测试", businessType = BusinessType.UPDATE)
    @PutMapping
    //@ApiOperation("修改")
    public AjaxResult edit(@RequestBody SmartTest smartTest)
    {
        if(containsSqlInjection(smartTest)) return AjaxResult.success("数据不正常");
        return toAjax(smartTestService.updateSmartTest(smartTest));
    }

    /**
     * 删除测试
     */
    @PreAuthorize("@ss.hasPermi('system:test:remove')")
    @Log(title = "测试", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    //@ApiOperation("删除")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        if(containsSqlInjection(ids)) return AjaxResult.success("数据不正常");
        return toAjax(smartTestService.deleteSmartTestByIds(ids));
    }

    /**
     * 插入工序数据
     */
    @GetMapping("/insertString/{data}")
    @ApiOperation("插入工序数据接口")
    public AjaxResult insertString(@PathVariable("data") String data)
    {
        if(containsSqlInjection(data)) return AjaxResult.success("数据不正常");
        smartProcessDataService.insertString(data);
        return AjaxResult.success();
    }
    /**
     * 扫码入库
     */
    @GetMapping("/scanCodeIn/{data}")
    @ApiOperation("扫码入库")
    public AjaxResult scanCodeIn(@PathVariable("data") String data)
    {
        if(containsSqlInjection(data)) return AjaxResult.error("数据不正常");
        if(data.contains("SN:")){
            String[] strs=data.split("SN:");
            data=strs[1];
        }
        SmartProduct smartProduct =new SmartProduct();
        smartProduct.setCode(data);
        List<SmartProduct> list=smartProductService.selectSmartProductList(smartProduct);
        if(list.size()>0){
            if(!"1".equals(list.get(0).getInventoryState()))
            {
                return AjaxResult.error("已经入库过了");
            }
            list.get(0).setInventoryState("2");
            smartProductService.updateSmartProduct(list.get(0));
        }
        System.out.println("扫码入库:"+data);
        return AjaxResult.success();
    }

    /**
     * 扫码出库
     */
    @GetMapping("/scanCodeOut/{data}")
    @ApiOperation("扫码出库")
    public AjaxResult scanCodeOut(@PathVariable("data") String data)
    {
        if(containsSqlInjection(data)) return AjaxResult.success("数据不正常");
        if(data.contains("SN:")){
            String[] strs=data.split("SN:");
            data=strs[1];
        }
        SmartProduct smartProduct =new SmartProduct();
        smartProduct.setCode(data);
        List<SmartProduct> list=smartProductService.selectSmartProductList(smartProduct);
        if(list.size()>0){
            if(!"2".equals(list.get(0).getInventoryState()))
            {
                return AjaxResult.error("已经出库过了，或者还未入库");
            }
            list.get(0).setInventoryState("3");
            smartProductService.updateSmartProduct(list.get(0));
        }
        System.out.println("扫码出库:"+data);
        return AjaxResult.success();
    }

    /**
     * 插入测试数据
     */
    @PostMapping("/insertTesting")
    @ApiOperation("插入测试数据接口")
    public AjaxResult insertTesting(@RequestBody JSONObject data)
    {
        if(containsSqlInjection(data)) return AjaxResult.success("数据不正常");
        System.out.println("测试数据接口:"+data.toJSONString());
        SmartModData smartModData=new SmartModData();
        smartModData.setTimeIn(new Date());
        if(data.containsKey("type")){
            if("mtr".equals(data.getString("type"))){
                smartModData.setType(data.getString("type"));
                //smartModData.setData(data.toJSONString());
                if(data.containsKey("ModStr"))
                    smartModData.setModStr(data.getJSONObject("ModStr").toJSONString());
                //在这里写入产品ID
                if(data.containsKey("ModList"))
                {
                    smartModData.setModList(data.getJSONArray("ModList").toJSONString());
                    JSONArray jsonArray=data.getJSONArray("ModList");
                    JSONObject jsonObject=jsonArray.getJSONObject(0);
                    if(jsonObject.containsKey("switch id")){
                        smartModData.setProductId(jsonObject.getString("switch id"));
                    }
                }

//                if(data.containsKey("data")){
//                    JSONArray jsonArray=data.getJSONArray("data");
//                    JSONObject jsonObject=jsonArray.getJSONObject(0);
//                    if(jsonObject.containsKey("switch id")){
//                        smartModData.setProductId(jsonObject.getString("switch id"));
//                    }
//                }
                smartModData.setTimeIn(new Date());
                smartModData.setState("0");
                smartModDataService.insertSmartModData(smartModData);
                //处理产品检验状态
                //smartProductTestRecordService.setState(data);
            }
            else if(data.containsKey("data"))
            {
                smartModData.setData(data.getJSONArray("data").toJSONString());
                if(data.containsKey("type"))
                {
                    smartModData.setType(data.getString("type"));
                }
                //在这里写入产品ID
                if(data.containsKey("ModStr"))
                {
                    smartModData.setModStr(data.getJSONArray("ModStr").toJSONString());
                    JSONArray jsonArray=data.getJSONArray("ModStr");
                    for(int i=0;i<jsonArray.size();i++)
                    {
                        JSONObject jsonObject=jsonArray.getJSONObject(i);
                        if(jsonObject.containsKey("Id")){
                            smartModData.setProductId("20"+jsonObject.getString("Id"));
                            break;
                        }
                    }
                }
                if(data.containsKey("ModList"))
                {
                    smartModData.setModList(data.getJSONObject("ModList").toJSONString());
                }
                smartModData.setTimeIn(new Date());
                smartModData.setState("0");
                smartModDataService.insertSmartModData(smartModData);
                //System.out.println(smartModData.getModList());
            }
        }


        return AjaxResult.success();
    }

    /**
     * 插入测试数据
     */
    @PostMapping("/boardMtr")
    @ApiOperation("看板数据1")
    public AjaxResult boardMtr(SmartModData smartModData)
    {
        return AjaxResult.success(smartModDataService.selectSmartModDataListTop10Mtr(smartModData));
    }

    /**
     * 插入测试数据
     */
    @PostMapping("/boardMtrWI")
    @ApiOperation("看板数据1")
    public AjaxResult boardMtrWI(SmartModData smartModData)
    {
        return AjaxResult.success(smartModDataService.selectSmartModDataListTop10Mtr(smartModData));
    }

    /**
     * 插入测试数据
     */
    @PostMapping("/boardMtrFT")
    @ApiOperation("看板数据1")
    public AjaxResult boardMtrFT(SmartModData smartModData)
    {
        return AjaxResult.success(smartModDataService.selectSmartModDataListTop10Mtr(smartModData));
    }

    /**
     * 插入测试数据
     */
    @PostMapping("/boardMtrHT")
    @ApiOperation("看板数据1")
    public AjaxResult boardMtrHT(SmartModData smartModData)
    {
        return AjaxResult.success(smartModDataService.selectSmartModDataListTop10Mtr(smartModData));
    }

    /**
     * 插入测试数据
     */
    @PostMapping("/boardGdf")
    @ApiOperation("看板数据2")
    public AjaxResult boardGdf(SmartModData smartModData)
    {
        return AjaxResult.success(smartModDataService.selectSmartModDataGdf(smartModData));
    }

    @PostMapping("/boardGdfWI")
    @ApiOperation("看板数据2")
    public AjaxResult boardGdfWI(SmartModData smartModData)
    {
        return AjaxResult.success(smartModDataService.selectSmartModDataGdf(smartModData));
    }

    @PostMapping("/boardGdfFT")
    @ApiOperation("看板数据2")
    public AjaxResult boardGdfFT(SmartModData smartModData)
    {
        return AjaxResult.success(smartModDataService.selectSmartModDataGdf(smartModData));
    }

    @PostMapping("/boardGdfHT")
    @ApiOperation("看板数据2")
    public AjaxResult boardGdfHT(SmartModData smartModData)
    {
        return AjaxResult.success(smartModDataService.selectSmartModDataGdf(smartModData));
    }

    /**
     * 是否含有sql注入，返回true表示含有
     *
     * @param obj
     * @return
     */
    public static boolean containsSqlInjection(Object obj) {
        Pattern pattern = Pattern.compile(
                "\\b(and|exec|insert|select|drop|grant|alter|delete|update|count|chr|mid|master|truncate|char|declare|or)\\b|(\\*|;|\\+|'|%)");
        Matcher matcher = pattern.matcher(obj.toString());
        return matcher.find();
    }
}
